﻿<template>
  <a-card :bordered="false">
    <a-modal
      title="导入数据"
      width="30%"
      :visible="visible"
      :confirmLoading="loading"
      @cancel="
        () => {
          this.visible = false
        }
      "
    >
      <div class="flax">
        <a-upload
          name="file"
          :multiple="true"
          :action="$rootUrl + '/CostManagement/cost_object/ImportData'"
          :headers="headers"
          @change="handleChange"
        >
          <a-button style="margin-left: 8px">
            <a-icon type="upload"/>
            导入数据
          </a-button>
        </a-upload>
        <div class="download">
          <a-button
            style="margin-left: 8px"
            @click="
              exportExcel($rootUrl + '/CustomerManagement/Cust_CustomerLinkMan/ExportTemplateToExcel', '客户联系人模板')
            "
          >
            <a-icon type="download"/>
            下载模板
          </a-button>
        </div>
      </div>
    </a-modal>
    <div class="table-operator">
      <a-button
        v-if="hasPerm('Cust_CustomerLinkMan.Add')"
        style="margin-bottom: 15px;"
        type="primary"
        icon="plus"
        @click="handleAdd()"
      >新建
      </a-button>
      <a-button
        style="margin-left: 8px;"
        type="primary"
        icon="minus"
        v-if="hasPerm('Cust_CustomerLinkMan.Delete')"
        @click="handleDelete(selectedRowKeys)"
        :disabled="!hasSelected()"
        :loading="loading"
      >删除
      </a-button>

      <a-button
        style="margin-left: 8px;"
        type="primary"
        icon="redo"
        @click="getDataList()"
        v-if="hasPerm('Cust_CustomerLinkMan.flushed')"
      >刷新
      </a-button>
      <a-button
        style="margin-left: 8px"
        @click="openhtml(selectedRowKeys)"
        :disabled="!hasSelected()"
        type="primary"
      >导出数据
      </a-button>
      <a-button
        style="margin-left: 8px"
        @click="
          () => {
            this.visible = true
          }
        "
        type="primary"
        v-if="hasPerm('Cust_CustomerLinkMan.Import')"
      >导入数据
      </a-button>
      <!-- <a-upload
        name="file"
        :multiple="true"
        :action="$rootUrl + '/CustomerManagement/Cust_CustomerLinkMan/ImportCustomerLinkManToDataBaseOfAll'"
        :headers="headers"
        @change="handleChange"
      >
        <a-button style="margin-left: 8px"> <a-icon type="upload" />导入数据</a-button>
      </a-upload> -->
    </div>

    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item label="查询类别">
              <a-select allowClear v-model="queryParam.condition">
                <a-select-option key="Name">姓名</a-select-option>

                <a-select-option key="Tel_Code">电话</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input @keydown="inputKeyDown" v-model="queryParam.keyword" placeholder="关键字"/>
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
            >查询
            </a-button>
            <a-button style="margin-left: 8px" @click="Repossess">重置</a-button>
          </a-col>
          <!-- <div class="download">
            <a-button
              style="margin-left: 8px"
              @click="
                exportExcel(
                  $rootUrl + '/CustomerManagement/Cust_CustomerLinkMan/ExportTemplateToExcel',
                  '客户联系人模板'
                )
              "
              ><a-icon type="download" />下载模板
            </a-button>
          </div> -->
        </a-row>
      </a-form>
    </div>
    <a-table
      id="tables"
      ref="table"
      :scroll="{ y: 530 }"
      :columns="columns"
      :rowKey="(row, index) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="true"
      size="small">
      <template slot="dataindex" slot-scope="text, record, index">
        {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
      </template>
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a v-if="hasPerm('Cust_CustomerLinkMan.Edit')" @click="handView(record.Id)">查看</a>
          <a-divider type="vertical" v-if="hasPerm('Cust_CustomerLinkMan.Edit')"/>
          <a v-if="hasPerm('Cust_CustomerLinkMan.Edit')" @click="handleEdit(record.Id)">编辑</a>
          <a-divider type="vertical" v-if="hasPerm('Cust_CustomerLinkMan.Edit')"/>
          <a v-if="hasPerm('Cust_CustomerLinkMan.Delete')" @click="handleDelete([record.Id])">删除</a>
        </template>
      </span>
    </a-table>
    <leading-show
      ref="leadingShow"
      :parentObj="this"
      leading="/CustomerManagement/Cust_CustomerLinkMan/Import"
      templet="/CustomerManagement/Cust_CustomerLinkMan/ExportToExcel"
    ></leading-show>
    <edit-form :row="row" ref="editForm" :parentObj="this"></edit-form>
  </a-card>
</template>

<script>
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import Token from '@/utils/cache/TokenCache'
import { download } from '@/components/download'
import EditForm from './EditForm'
import leadingShow from './leadingShow.vue'
import moment from 'moment'

function exportExcel (res, title) {
  const data = res.data || res || {}
  const blob = new Blob([data], {
    type: 'application/vnd.ms-excel' // 设置为excel格式
  })
  const url = window.URL.createObjectURL(blob)
  const fileName = title
  const aTag = document.createElement('a')
  aTag.download = fileName
  aTag.href = url
  aTag.click()
  URL.revokeObjectURL(aTag.href)
  // v.$message.success("导出成功!");
}

const columns = [
  { title: '序号', dataIndex: 'dataindex', width: '50px', align: 'center', scopedSlots: { customRender: 'dataindex' } },
  { title: '所属客户', dataIndex: 'CustomerName' },
  { title: '姓名', dataIndex: 'Name', align: 'center' },
  { title: '组织机构', dataIndex: 'Department', width: '150px' },
  { title: '职位', dataIndex: 'Position', width: '100px' },
  { title: '详细地址', dataIndex: 'Address', ellipsis: true },
  { title: '电话', dataIndex: 'Tel_Code', width: '120px' },
  { title: '角色名称', dataIndex: 'RoleName', width: '100px' },
  // { title: '备注', dataIndex: 'Remark', width: '140px' },
  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, width: '150px' }
]

export default {
  components: {
    EditForm,
    leadingShow,
    Token
  },

  data () {
    return {
      visible1: false,
      visible: false,
      headers: {
        authorization: 'Bearer ' + Token.getToken()
      },
      title: '',
      row: {},
      data: [],
      list: [], // 省级
      listChildren: [], // 市
      county: [], // 县
      CustomerId: '',
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: { field: 'Id', order: 'desc' },
      loading: false,
      columns,
      id: '',
      queryParam: {
        condition: 'Name'
      },
      selectedRowKeys: []
    }
  },
  mounted () {
    this.getDataList()
    this.getlist()
  },
  methods: {
    inputKeyDown (e) {
      if (e.keyCode === 13) {
        if (!this.queryParam.keyword) return this.$message.error('请输入查询条件')

        this.getDataList()
      }
    },
    // load() {
    //   this.$http.post('/CustomerManagement/Cust_CustomerLinkMan/ExportTemplateToExcel').then(resJson => {
    //     this.loading = false

    //     exportExcel(this.$rootUrl + '/CustomerManagement/Cust_CustomerLinkMan/ExportTemplateToExcel', '客户联系人模板')
    //   })
    // },
    Repossess () {
      this.queryParam = { condition: 'Name' }
      this.getDataList();
    },
    // 市级change
    city (e) {
      this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=' + e, {}).then(resJson => {
        this.loading = false
        this.listChildren = resJson.Data
      })
    },

    // 县change
    village (e) {
      this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=' + e, {}).then(resJson => {
        this.loading = false

        this.county = resJson.Data
      })
    },
    // 获取省份信息
    getlist (e) {
      this.$http.post('/Base_BasicData/Base_District/GetDataListByPId?pId=0', {}).then(resJson => {
        this.loading = false
        this.list = resJson.Data

        // this.getlistUser()
      })
    },
    // 导出当前数据
    outTab () {
      /* generate workbook object from table */
      const wb = XLSX.utils.table_to_book(document.querySelector('#tables'))
      /* get binary string as output */
      const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '客户联系人.xls')
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    // 导出全部数据
    openhtml (ids) {
      // window.location.href = '/CustomerManagement/Cust_CustomerLinkMan/ExportCustomerLinkManToExcel'
      this.$http({
        url: '/CustomerManagement/Cust_CustomerLinkMan/ExportCustomerLinkManToExcel',
        method: 'post',
        data: ids
      }).then(resJson => {
        //  responseType: 'blob'

        window.location.href = resJson.Data.fileUrl
        exportExcel(resJson, '客户联系人信息')
      })
    },

    exportExcel (url, tit) {
      download(url, tit)
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      this.getDataList()
    },
    getDataList () {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/CustomerManagement/Cust_CustomerLinkMan/GetDataListOfMySelfCustomerInfoByConditions', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order, DeptId: this.DeptId,
          Search: [this.queryParam],
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.data = resJson.Data
          this.CustomerId = this.data.CustomerId
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    hanldleLeading () {
      this.$refs.leadingShow.openForm(null, '客户信息')
    },
    init () {
      this.visible1 = true
    },
    openForm (row, title) {
      this.init()
      this.title = title
      this.row = row
      if (row) {
        this.id = row.Id
        // this.cCusName = row.cCusName
        this.loading = true
        this.$http
          .post('/CustomerManagement/Cust_CustomerLinkMan/GetDataListByConditions', {
            PageIndex: this.pagination.current,
            PageRows: 999,
            SortField: this.sorter.field || 'Id',
            SortType: this.sorter.order, DeptId: this.DeptId,
            Search: [this.queryParam],
            ...this.filters
          })
          .then(resJson => {
            this.loading = false
            this.data = resJson.Data
            if (this.data) {
              const pagination = { ...this.pagination }
              pagination.total = resJson.Total
              this.pagination = pagination
            }
          })
      }
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    handleAdd () {
      this.$refs.editForm.openForm(null, '新建客户联系人信息')
    },
    // 导入文件类型
    handleChange (info) {
      if (info.file.status !== 'uploading') {
      }
      if (info.file.status === 'done') {
        if (info.file.response.Success === false) {
          this.$message.error(`${info.file.name}文件,${info.file.response.Msg},请检查文件内容！ `)
        } else {
          this.$message.success(`${info.file.name}  文件上传成功！`)
          this.getDataList()
        }
        this.visible = false
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败！`)
      }
    },
    handleEdit (id) {
      this.$refs.editForm.openForm(id, '编辑客户联系人信息')
    },
    handView (id) {
      this.$refs.editForm.openForm(id, '查看客户联系人信息')
    },
    handleDelete (ids) {
      var thisObj = this
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
       return new Promise((resolve, reject) => {
          thisObj.$http.post('/CustomerManagement/Cust_CustomerLinkMan/DeleteData', ids).then(resJson => {
            resolve()
            if (resJson.Success) {
              thisObj.$message.success('操作成功!')
              thisObj.getDataList()
            } else {
              thisObj.$message.error(resJson.Msg)
            }
          })
        })
      })
    },
    timeFormat (val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD HH:mm')
    }
  }
}
</script>

<style scoped>
.flax {
  display: flex;
  justify-content: space-between;
}

/* .download {
  float: right;
  display: flex;
  align-items: center;
} */
</style>
